

import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
import org.apache.commons.fileupload.FileItemFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.sun.jndi.toolkit.ctx.Continuation;

import dataMgr.User;
import dataMgr.UserManager;

//import dataMgr.User;
//import dataMgr.UserManager;





/**
 * Servlet implementation class UploadServlet
 */

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 50 * 1024;	// optional
	private int maxMemSize = 4 * 1024; // optional
	private File file ;

	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init( ){
    	// Get the file location where it would be stored.
    	filePath =  getServletContext().getInitParameter("file-upload");
    	if(null==filePath)
    		filePath="";
    	   }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		
		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");


		
		// Check that we have a file upload request
		isMultipart = ServletFileUpload.isMultipartContent(request);
		response.setContentType("text/html");
		java.io.PrintWriter out = response.getWriter( );
		if( !isMultipart ){

			out.println("No file uploaded");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		//factory.setSizeThreshold(maxMemSize); // optional
		// Location to save data that is larger than maxMemSize.
		//factory.setRepository(new File("//")); // optional

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		//upload.setSizeMax( maxFileSize );

		try{ 
			// Parse the request to get file items.
			List<FileItem> fileItems = upload.parseRequest(request);
			// Process the uploaded file items
			Iterator<FileItem> i = fileItems.iterator();

			while ( i.hasNext () ) 
			{
				FileItem fi = i.next();
				if ( !fi.isFormField () )	
				{
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					
					String temp_file_path=fileName;
					System.out.println("file path:"+temp_file_path);
					
					String contentType = fi.getContentType();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if( fileName.lastIndexOf("\\") >= 0 ){

						file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
					}else{
						file = new File( filePath +  fileName.substring(fileName.lastIndexOf("\\")+1)) ;
					}

					out.println("bye");
					// fi.write( file ) ; // optional - writes in memory (mapped file) if its size is less than maxMemSize  

					// physical write, please use buffer for this...
					InputStream in=fi.getInputStream();
					if(fileName.lastIndexOf("\\")>0)
						fileName=fileName.substring(fileName.lastIndexOf("\\"));

					
					SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
					Session session = sessionFactory.openSession();
					Query query1 = session.createQuery("select max(g.fileID) from Lib g ");
					java.util.List <Long>list1 = query1.list();
					Long max;
					if(list1==null || list1.isEmpty())
						max=(long) 0;
					else
						max= list1.get(0);
						
					if(max==null)
						max=(long) 0;	
					
					String type=fileName.substring(fileName.lastIndexOf("."));
					FileOutputStream outf=new FileOutputStream("c:\\temp\\"+max+type);
					
					int data;
					while((data=in.read())!=-1){
						outf.write(data);
					}
					in.close();
					outf.close();

					out.println("Uploaded Filename: " + fileName );
					//MessageSender.getInstance().send("blabla", "file uploaded ->"+fileName);
					
					
					//finding all the users that should be informed about the changes
					Query query2 = session.createQuery("select g.userName from Group g where g.groupID = "+ConnectionsHolder.getInstance().last_group);
					List<String> users=query2.list();
					
					synchronized(ConnectionsHolder.getInstance())
					{
						ConnectionsHolder.getInstance().last_file_id=max;	
						ConnectionsHolder.getInstance().last_file_path=temp_file_path;
						
						
					}
					synchronized(ConnectionsHolder.getInstance().connections)
					{
						int length=ConnectionsHolder.getInstance().connections.size();
						for(int ii=0;ii<length;ii++)
						{	
							
							//if(users.contains(ConnectionsHolder.getInstance().users.get(ii)))
							ConnectionsHolder.getInstance().connections.get(ii).resume();
						}
					}
				}
				
/*

				User tag=new User();
				tag.setUserName("bbbbbbbjbbbbb");
				tag.setPassword("678");

				System.out.println("dddd");
				SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 

				Session session = sessionFactory.openSession();
				UserManager manager = new UserManager(session);
				manager.saveUser(tag);*/
			}

		}catch(Exception ex) {
			// System.out.println(ex);
		}



	}

	
	}


